package com.socialuni.sdk.user.phone;

import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.user.authCode.AuthCodeCheck;
import com.socialuni.sdk.model.BindPhoneVO;
import com.socialuni.sdk.repository.UserRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

//授权用户信息
@Service
public class SocialBindPhoneNumDomain {
    @Resource
    SocialPhoneNumCheck socialPhoneNumCheck;
    @Resource
    SocialPhoneNumManage socialPhoneNumManage;
    @Resource
    private AuthCodeCheck authCodeCheck;
    @Resource
    private UserRepository userRepository;

    //  分连个业务，一个是手机号登录，一个是绑定手机号。 绑定手机号的时候，提示手机号已被使用就行了。登录的时候才提示被封禁，这里只是绑定手机号的逻辑
    public UserDO checkAuthCodeAndUserBindPhoneNum(BindPhoneVO bindPhoneVO, UserDO mineUser) {
        //登录的时候如果没有手机号，则手机号注册成功，自动注册一个user，用户名待填，自动生成一个昵称，密码待填，头像待上传
        //如果已经登录过，则返回那个已经注册的user，根据手机号获取user，返回登录成功
        //记录用户错误日志
        String authCode = bindPhoneVO.getAuthCode();

        String phoneNum = bindPhoneVO.getPhoneNum();

        authCodeCheck.checkAuthCode(phoneNum, authCode);

        mineUser = checkPhoneNumAndUserBindPhoneNum(mineUser, "86", phoneNum);
        return mineUser;
    }


    public UserDO checkPhoneNumAndUserBindPhoneNum(UserDO mineUser, String phoneCountryCode, String phoneNum) {
        //业务校验
        //校验手机号是否已被使用
        socialPhoneNumCheck.checkPhoneNum(phoneNum, mineUser);

        socialPhoneNumManage.createUserPhoneNum(mineUser, phoneCountryCode, phoneNum);

        mineUser.setUpdateTime(new Date());
        mineUser = userRepository.save(mineUser);
        return mineUser;
    }
}
